package com.zerox.controller;

import com.zerox.pojo.SysUser;
import com.zerox.service.SupplierService;
import com.zerox.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/login")
    public String toLogin(){
        return "login";
    }
    @GetMapping("/tolist")
    public String toList(){
        return "list";
    }

    // 处理登录的请求
    @PostMapping("/login")
    public String doLogin(HttpSession session, Model model, String username, String password,String loginId){
        SysUser sysUser = sysUserService.login(username, password);

        if (sysUser != null){
            session.setAttribute("username",sysUser.getRealName());

            if (loginId.equals("1")) {
                return "redirect:/user/tolist";
            }
            if (loginId.equals("2")) {
                return "redirect:/supplier/tolist";
            }
        }

        model.addAttribute("errorMsg","用户名或密码错误");

        return "login";
    }

    //局部异常处理
    @ExceptionHandler(RuntimeException.class)
    public String handlerException(Model model,RuntimeException e){

        model.addAttribute("errorMsg",e.getMessage());

        return "error";
    }
}
